<template>
  <div>
    <!-- 搜索表单 -->
    <div style="margin-bottom: 20px">
      <span style="margin-right: 5px">书名/ISBN/编号/作者名：</span>
      <i-input v-model="searchQuery" placeholder="输入书名、ISBN 编号或作者名" style="width: 200px; margin-right: 10px" />
      <i-button type="primary" icon="ios-search" @click="handleSearch">搜索</i-button>
      <i-button type="default" icon="ios-refresh" @click="resetSearch" style="margin-left: 10px">重置</i-button>
      <!-- 只有管理员可以看到添加图书按钮 -->
      <!-- <i-button v-if="user.userRole === 'admin'" type="success" icon="ios-add" @click="showAddBookModal = true" style="float: right"
        >添加图书</i-button
      > -->
    </div>
    <!-- 只有管理员可以看到添加图书按钮 -->
    <div style="margin-bottom: 10px">
      <i-button v-if="user.userRole === 'admin'" type="success" icon="ios-add" @click="showAddBookModal = true"> 添加 </i-button>
    </div>

    <i-table :columns="columns" :data="filteredData" border>
      <template #bookName="{ row }">
        <strong>{{ row.bookName }}</strong>
      </template>
      <template #bookIsbn="{ row }">
        {{ row.bookIsbn }}
      </template>
      <template #bookPress="{ row }">
        {{ row.bookPress }}
      </template>
      <template #bookAuthor="{ row }">
        {{ row.bookAuthor }}
      </template>

      <template #bookPagination="{ row }">
        {{ row.bookPagination }}
      </template>

      <template #bookPrice="{ row }">
        {{ row.bookPrice }}
      </template>

      <template #bookStatus="{ row }">
        {{ row.bookStatus === "0"? "未借阅" : "已借阅" }}
      </template>
      <template #bookBorrower="{ row }">
        {{ row.bookBorrower || "无" }}
      </template>
      <template #bookBorrowtime="{ row }">
        {{ row.bookBorrowtime ? new Date(row.bookBorrowtime).toLocaleString() : "无" }}
      </template>
      <template #bookReturntime="{ row }">
        {{ row.bookReturntime ? new Date(row.bookReturntime).toLocaleString() : "无" }}
      </template>
      <template #action="{ row }">
        <!-- 如果是管理员，显示删除和修改按钮 -->
        <div v-if="user.userRole === 'admin'">
          <Button type="error" size="small" @click="removeBook(row.bookId)">删除</Button>
          <Button type="primary" size="small" style="margin-left: 8px" @click="openEditBookModel(row)">编辑</Button>
        </div>
        <!-- 如果是普通用户，根据 bookStatus 显示借阅按钮 -->
        <div v-else>
          <Button :disabled="row.bookStatus === '1'" type="primary" size="small" @click="borrowBook(row.bookId)">
            {{ row.bookStatus === "1" ? "已借出" : "借阅" }}
          </Button>
        </div>
      </template>
    </i-table>

    <div class="pagination-container">
      <page
        :total="totalBooks"
        :current="currentPage"
        :page-size="pageSize"
        show-elevator
        show-total
        show-sizer
        @on-change="handlePageChange"
        :page-size-opts="pageSize"
      />
    </div>

    <!-- 添加图书 -->
    <Modal
      title="添加图书"
      @on-ok="handleAddBook"
      v-model="showAddBookModal"
      width="720"
      :mask-closable="false"
      :styles="modalStyles"
      @on-cancel="showAddBookModal = false"
    >
      <Form :model="addBookForm" ref="addBookForm" :rules="addBookRules">
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="图书名称" label-position="top" prop="bookName">
              <Input v-model="addBookForm.bookName" placeholder="请输入图书名称" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="ISBN 编号" label-position="top" prop="bookIsbn">
              <Input v-model="addBookForm.bookIsbn" placeholder="请输入 ISBN 编号" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="出版社" label-position="top" prop="bookPress">
              <Input v-model="addBookForm.bookPress" placeholder="请输入出版社" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="作者" label-position="top" prop="bookAuthor">
              <Input v-model="addBookForm.bookAuthor" placeholder="请输入作者" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="页数" label-position="top" prop="bookPagination">
              <Input v-model="addBookForm.bookPagination" type="number" placeholder="请输入页数" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="价格" label-position="top" prop="bookPrice">
              <Input v-model="addBookForm.bookPrice" type="number" placeholder="请输入价格" />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>

    <!-- 修改图书模态框 -->
    <Modal
      title="修改图书"
      v-model="showEditBookModal"
      width="720"
      :mask-closable="false"
      :styles="modalStyles"
      @on-cancel="showEditBookModal = false"
      @on-ok="handleUpdateBook"
    >
      <Form :model="editBookForm" ref="editBookForm" :rules="editBookRules">
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="图书名称" label-position="top" prop="bookName">
              <Input v-model="editBookForm.bookName" placeholder="请输入图书名称" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="ISBN 编号" label-position="top" prop="bookIsbn">
              <Input v-model="editBookForm.bookIsbn" placeholder="请输入 ISBN 编号" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="出版社" label-position="top" prop="bookPress">
              <Input v-model="editBookForm.bookPress" placeholder="请输入出版社" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="作者" label-position="top" prop="bookAuthor">
              <Input v-model="editBookForm.bookAuthor" placeholder="请输入作者" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="12">
            <FormItem label="页数" label-position="top" prop="bookPagination">
              <Input v-model="editBookForm.bookPagination" type="number" placeholder="请输入页数" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="价格" label-position="top" prop="bookPrice">
              <Input v-model="editBookForm.bookPrice" type="number" placeholder="请输入价格" />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { getAllbook, deleteBook, addBook, updateBook, borrowBook as borrowBookAPI } from "../api/library";
import { Modal, FormItem, Input, Button, Row, Col, Message } from "view-ui-plus";
import { userInfo } from "@/api/user";

export default {
  components: {
    Modal,
    FormItem,
    Input,
    Button,
    Row,
    Col,
    Message,
  },
  data() {
    return {
      user: {
        userRole: "", // 用于存储用户角色
      },
      columns: [
        { title: "图书名称", key: "bookName", slot: "bookName" },
        { title: "ISBN 编号", key: "bookIsbn", slot: "bookIsbn" },
        { title: "出版社", key: "bookPress", slot: "bookPress" },
        { title: "作者", key: "bookAuthor", slot: "bookAuthor" },
        { title: "页数", key: "bookPagination", slot: "bookPagination" },
        { title: "价格", key: "bookPrice", slot: "bookPrice" },
        { title: "状态", key: "bookStatus", slot: "bookStatus" },
        { title: "借阅者", key: "bookBorrower", slot: "bookBorrower" },
        { title: "借阅时间", key: "bookBorrowtime", slot: "bookBorrowtime" },
        { title: "归还时间", key: "bookReturntime", slot: "bookReturntime" },
        { title: "操作", slot: "action", width: 150, align: "center" },
      ],
      tableData: [],
      filteredData: [],
      searchQuery: "",
      totalBooks: 0,
      currentPage: 1,
      pageSize: 7,
      showAddBookModal: false,
      modalStyles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
      },
      addBookForm: {
        bookName: "",
        bookIsbn: "",
        bookPress: "",
        bookAuthor: "",
        bookPagination: null,
        bookPrice: null,
      },
      addBookRules: {
        bookName: [{ required: true, message: "图书名称不能为空", trigger: "blur" }],
        bookIsbn: [{ required: true, message: "ISBN 编号不能为空", trigger: "blur" }],
        bookPress: [{ required: true, message: "出版社不能为空", trigger: "blur" }],
        bookAuthor: [{ required: true, message: "作者不能为空", trigger: "blur" }],
        bookPagination: [{ required: true, message: "页数不能为空", trigger: "blur" }],
        bookPrice: [{ required: true, message: "价格不能为空", trigger: "blur" }],
      },
      showEditBookModal: false,
      editBookForm: {
        bookId: 0,
        bookName: "",
        bookIsbn: "",
        bookPress: "",
        bookAuthor: "",
        bookPagination: null,
        bookPrice: null,
        bookStatus: "0",
        bookBorrower: null,
        bookBorrowtime: null,
        bookReturntime: null,
      },
      editBookRules: {
        bookName: [{ required: true, message: "图书名称不能为空", trigger: "blur" }],
        bookIsbn: [{ required: true, message: "ISBN 编号不能为空", trigger: "blur" }],
        bookPress: [{ required: true, message: "出版社不能为空", trigger: "blur" }],
        bookAuthor: [{ required: true, message: "作者不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    getCookieToken() {
      return document.cookie
        .split("; ")
        .find((row) => row.startsWith("token="))
        ?.split("=")[1];
    },
    getData() {
      const token = this.getCookieToken();
      if (token) {
        getAllbook(token).then((res) => {
          this.tableData = res.data;
          this.totalBooks = res.data.length;
          this.updateFilteredData(); // 更新当前页显示的数据
        });
      } else {
        Message.error("无法获取令牌，请重新登录");
      }
    },

    updateFilteredData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.filteredData = this.tableData.slice(start, end); // 切片数据
    },

    handlePageChange(page) {
      this.currentPage = page; // 更新当前页
      this.updateFilteredData(); // 更新当前页显示的数据
    },

    handleSearch() {
      const query = this.searchQuery.trim().toLowerCase();
      this.filteredData = this.tableData.filter((book) => {
        return book.bookName.toLowerCase().includes(query) || book.bookIsbn.toLowerCase().includes(query);
      });
    },
    resetSearch() {
      this.searchQuery = ""; // 清空搜索框内容
      this.filteredData = this.tableData; // 重置过滤后的数据为全部数据
      this.currentPage = 1; // 重置到第一页
      this.updateFilteredData(); // 更新分页
    },
    removeBook(id) {
      const token = this.getCookieToken();
      if (token) {
        deleteBook(id, token)
          .then((res) => {
            if (res.code === 0) {
              Message.success("删除成功");
              this.getData();
            } else {
              Message.error("删除失败：" + res.message);
            }
          })
          .catch((error) => {
            console.error("删除书籍失败：", error);
            Message.error("删除失败，请重试");
          });
      } else {
        Message.error("无法获取令牌，请重新登录");
      }
    },
    handleAddBook() {
      const token = this.getCookieToken();
      this.$refs.addBookForm.validate((valid) => {
        if (valid) {
          addBook(this.addBookForm, token)
            .then((res) => {
              if (res.code === 0) {
                Message.success("添加成功");
                this.showAddBookDrawer = false;
                this.getData();
              } else {
                Message.error("添加失败：" + res.message);
              }
            })
            .catch((error) => {
              console.error("添加书籍失败：", error);
              Message.error("添加失败，请重试");
            });
        } else {
          return false;
        }
      });
    },

    openEditBookModel(book) {
      // 加载当前图书的信息
  this.editBookForm = { ...book };
      this.originalBookData = { ...book }; // 存储原始数据
      this.showEditBookModal = true;
    },
    handleUpdateBook() {
      const token = this.getCookieToken();
      this.$refs.editBookForm.validate((valid) => {
        if (valid) {
          // 创建一个只包含已更改字段的对象
          const changedFields = { bookId: this.editBookForm.bookId };
          Object.keys(this.editBookForm).forEach(key => {
            if (this.editBookForm[key] !== this.originalBookData[key]) {
              changedFields[key] = this.editBookForm[key];
            }
          });

          console.log("更新的字段：", changedFields);

          updateBook(changedFields, token)
            .then((res) => {
              if (res.code === 0) {
                Message.success("修改成功");
                this.showEditBookModal = false;
                this.getData(); // 刷新数据
              } else {
                Message.error("修改失败：" + res.message);
              }
            })
            .catch((error) => {
              console.error("修改书籍失败：", error);
              Message.error("修改失败，请重试");
            });
        } else {
          return false;
        }
      });
    },

    //借阅书籍
    borrowBook(bookId) {
      const token = this.getCookieToken();
      borrowBookAPI(bookId, token)
        .then((res) => {
          if (res.code === 0) {
            Message.success("借阅成功");
            this.getData();
          } else {
            Message.error("借阅失败：" + res.message);
          }
        })
        .catch((error) => {});
    },
  },
  created() {
    // 获取用户信息
    const token = document.cookie
      .split("; ")
      .find((row) => row.startsWith("token="))
      ?.split("=")[1];
    userInfo(token).then((res) => {
      if (res.code === 0) {
        //用于判断
        this.user = res.data; // 将获取到的用户信息存储在 user 变量中
      } else {
        this.$Message.error("无法获取用户信息");
      }
    });
    this.getData();
  },
};
</script>

<style scoped>
.drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.pagination-container {
  position: fixed;
  bottom: 40px; /* 距离底部的距离 */
  right: 48px; /* 距离右边的距离 */
}
</style>
